package com.kpx.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.AddressBean;
import com.kpx.app.bean.OrderBean;
import com.kpx.app.bean.RequirementMapBean;
import com.kpx.app.bean.TaskBean;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by congdy on 17/3/3.
 * 订单确认
 */

public class ActivityOrderSure extends ActivityBase {
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.txt_no_address_mention)
    TextView txtNoAddressMention;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.ll_show_address)
    LinearLayout llShowAddress;
    @BindView(R.id.ll_change_address)
    LinearLayout llChangeAddress;
    @BindView(R.id.img_task)
    ImageView imgTask;
    @BindView(R.id.txt_pro_name)
    TextView txtProName;
    @BindView(R.id.txt_sex)
    TextView txtSex;
    @BindView(R.id.txt_age)
    TextView txtAge;
    @BindView(R.id.txt_height)
    TextView txtHeight;
    @BindView(R.id.txt_weight)
    TextView txtWeight;
    @BindView(R.id.txt_danbao_price)
    TextView txtDanbaoPrice;
    @BindView(R.id.txt_yongjin_price)
    TextView txtYongjinPrice;
    @BindView(R.id.txt_request)
    TextView txt_request;
    @BindView(R.id.txt_return)
    TextView txt_return;
    @BindView(R.id.task_mention)
    TextView task_mention;
    @BindView(R.id.btn_suborder)
    Button btnSuborder;
    @BindView(R.id.txt_star)
    TextView txtStar;
    @BindView(R.id.txt_shose_size)
    TextView txtShoseSize;
    @BindView(R.id.txt_yj)
    TextView txtYj;
    private TaskBean taskBean;
    AddressBean address;
    private int GET_ADDRESS = 100;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_sure);
        ButterKnife.bind(this);
        UIUtils.setNormalTitle(titleview, "订单确认");
    }

    @Override
    public void initData() {
        taskBean = (TaskBean) getIntent().getExtras().getSerializable(Constants.KEY_TASK_BEAN);
        if (taskBean != null) {
            Glide.with(this).load(taskBean.getTaskGoods().getMainPic()).into(imgTask);
            txtProName.setText(taskBean.getTaskGoods().getGoodsName());
            txtAge.setText("年龄：" + (taskBean.getRequirementMap() == null || UIUtils.isEmptyTask(taskBean.getRequirementMap().getAge()) ? "不限" : (taskBean.getRequirementMap().getAge() + "")));
            txtHeight.setText("身高：" + (taskBean.getRequirementMap() == null || UIUtils.isEmptyTask(taskBean.getRequirementMap().getHeight()) ? "不限" : taskBean.getRequirementMap().getHeight() + ""));
            txtSex.setText("性别：" + getSex(taskBean.getRequirementMap()));
            txtWeight.setText("体重：" + (taskBean.getRequirementMap() == null || UIUtils.isEmptyTask(taskBean.getRequirementMap().getWeight()) ? "不限" : taskBean.getRequirementMap().getWeight() + ""));
            txtStar.setText("等级：" + (taskBean.getRequirementMap() == null || UIUtils.isEmptyTask(taskBean.getRequirementMap().getLevel()) ? "不限" : taskBean.getRequirementMap().getLevel() + ""));
            txtShoseSize.setText("鞋码：" + (taskBean.getRequirementMap() == null || UIUtils.isEmptyTask(taskBean.getRequirementMap().getSize()) ? "不限" : taskBean.getRequirementMap().getSize() + ""));

            txt_request.setText(taskBean.getRequirementTxt());
            txt_return.setText("＊佣金包含退货运费   退货地址：" + taskBean.getRefundAddress());
            txtDanbaoPrice.setText(df.format(taskBean.getDeposit()));
            txt_return.setVisibility(taskBean.getTaskType() == 1 ? View.VISIBLE : View.GONE);
            txtYongjinPrice.setText(taskBean.getTaskType() == 1 ? df.format(taskBean.getCommission()) : "赠送实物");
            findViewById(R.id.txt_yj).setVisibility(taskBean.getTaskType() == 1 ? View.VISIBLE : View.GONE);
            if (taskBean.getTaskFollows() == 1) {
                task_mention.setText("注：抢单成功后请在30分钟之内完成担保金支付，否则订单自动取消");
            } else if (taskBean.getTaskFollows() == 2) {
                task_mention.setText("注：抢单成功后请使用已绑定的账号，在2小时内至第三方平台下单并提交第三方订单号，否则该单将被取消。");
            }
        }
        UserInfoUtils.getAddress(ActivityOrderSure.this, new UserInfoUtils.OnGetAddressdataBackListener() {
            @Override
            public void back(ArrayList<AddressBean> aBeans) {
                if (aBeans != null && aBeans.size() > 0) {
                    txtNoAddressMention.setVisibility(View.GONE);
                    llShowAddress.setVisibility(View.VISIBLE);
                    if (aBeans.size() == 1) {
                        txtName.setText("收货人：" + aBeans.get(0).getReceiver());
                        txtPhone.setText("电话：" + aBeans.get(0).getPhone());
                        txtAddress.setText("收货地址：" + aBeans.get(0).getRegion() + aBeans.get(0).getAddress());
                        ActivityOrderSure.this.address = aBeans.get(0);
                    } else {
                        for (int i = 0; i < aBeans.size(); i++) {
                            if (aBeans.get(i).getIsDefault() == 1) {
                                txtName.setText(aBeans.get(i).getReceiver());
                                txtPhone.setText(aBeans.get(i).getPhone());
                                txtAddress.setText("收货地址：" + aBeans.get(i).getRegion() + aBeans.get(i).getAddress());
                                ActivityOrderSure.this.address = aBeans.get(i);
                            }
                        }
                    }
                } else {
                    txtNoAddressMention.setVisibility(View.VISIBLE);
                }
            }
        });
        llChangeAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtil.gotoActivityForResult(ActivityOrderSure.this, ActivityOrderChoiceAddress.class, GET_ADDRESS);
            }
        });
    }

    DecimalFormat df = new DecimalFormat("###0.00");

    private String getSex(RequirementMapBean sex) {
        if (sex == null) {
            return "不限";
        }
        switch (sex.getSex()) {
            case 0:
                return "不限";
            case 1:
                return "男";
            case 2:
                return "女";
            default:
                return "不限";
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GET_ADDRESS && resultCode == RESULT_OK) {
            AddressBean taddress = (AddressBean) data.getSerializableExtra(getResources().getString(R.string.intent_key_bean));
            if (taddress != null) {
                txtNoAddressMention.setVisibility(View.GONE);
                llShowAddress.setVisibility(View.VISIBLE);
                address = taddress;
                txtName.setText("收货人：" + address.getReceiver());
                txtPhone.setText("电话：" + address.getPhone());
                txtAddress.setText("收货地址：" + address.getRegion() + address.getAddress());
            }
        }
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    @OnClick(R.id.btn_suborder)
    public void onClick() {
        if (address == null) {
            ToastUtil.getInstance().showToast(ActivityOrderSure.this, "您还没有设置收货地址，请先添加收货地址");
            return;
        }
        sureOrder(address);
    }

    /**
     * 确认订单
     *
     * @param addressBean
     */
    private void sureOrder(AddressBean addressBean) {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("taskId", taskBean.getDmId() + "");
        map.put("receiverInfoId", addressBean.getDmId() + "");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    OrderBean b = (OrderBean) result.getData();
                    if (b != null) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constants.KEY_ORDER_BEAN, b);
                        bundle.putSerializable(Constants.KEY_TASK_BEAN, taskBean);
                        if (b.getOrderStatus() == OrderBean.ORDER_STATUS_WAITTING_PAY) {
                            IntentUtil.gotoActivityAndFinish(ActivityOrderSure.this, ActivityPayList.class, bundle);
                        } else if (b.getOrderStatus() == OrderBean.ORDER_STATUS_WAITTING_FILL) {
                            ActivityOrderDetail.inType = 1;
                            IntentUtil.gotoActivityAndFinish(ActivityOrderSure.this, ActivityOrderDetail.class, bundle);
//                            IntentUtil.gotoActivityAndFinish(ActivityOrderSure.this, ActivityThirdOrderDo.class, bundle);
//                            IntentUtil.gotoActivityAndFinish(ActivityOrderSure.this, ActivitySetOrderInfo.class, bundle);
                        }
                        ToastUtil.getInstance().showToast(ActivityOrderSure.this, "抢单成功");
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityOrderSure.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                ToastUtil.getInstance().showToast(ActivityOrderSure.this, error);
                dissmissLoadingDialog();
            }

        }, OrderBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_GET_TASK, true, map);
//        showLoadingDialog();
//        MyHashMap map = new MyHashMap();
//        map.put("orderId", orderid);
//        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
//            @Override
//            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
//                dissmissLoadingDialog();
//                if (result.getCode() == 0) {
//                    IntentUtil.gotoActivity(ActivityOrderSure.this, ActivityPayList.class);
//                    ToastUtil.getInstance().showToast(ActivityOrderSure.this, "确认成功");
//                } else {
//                    ToastUtil.getInstance().showToast(ActivityOrderSure.this, result.getMsg());
//                }
//            }
//
//            @Override
//            public void onRequestError(String url, int statusCode, String error) {
//                dissmissLoadingDialog();
//                ToastUtil.getInstance().showToast(ActivityOrderSure.this, error);
//            }
//
//        }, null, null).POST(HttpDataReqUrl.URL_POST_SURE_ORDER, true, map);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
